package com.xadrez.sons;

import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;

public class Som extends Thread{

    private final static int EXTERNAL_BUFFER_SIZE = 10;//524288; // 128Kb 
    private static Som instance = null;
    private final static String PEGA = "./src/main/java/com/xadrez/sons/pick.wav";
    private final static String COLOCA = "./src/main/java/com/xadrez/sons/put.wav";
       
    public void tocouEmPeca() {
        toca(PEGA);
    }
    
    public void colocouPeca() {
        toca(COLOCA);
    }
    
    // <editor-fold defaultstate="collapsed" desc="MÉTODOS GERAIS">
    private Som(){
    }
    
    public synchronized static Som getInstance() {
        if (instance == null) {
            instance = new Som();
        }
        return instance;
    }

    private static void toca(String nomeArquivo) {
        File soundFile = new File(nomeArquivo);
        if (!soundFile.exists()) {
            System.err.println("Wave file not found:" + nomeArquivo);
            return;
        }

        AudioInputStream audioInputStream = null;
        try {
            audioInputStream = AudioSystem.getAudioInputStream(soundFile);
        } catch (Exception e1) {
            e1.printStackTrace();
            return;
        }

        AudioFormat format = audioInputStream.getFormat();
        SourceDataLine auline = null;
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

        try {
            auline = (SourceDataLine) AudioSystem.getLine(info);
            auline.open(format);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        auline.start();
        int nBytesRead = 0;
        byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];

        try {
            while (nBytesRead != -1) {
                nBytesRead = audioInputStream.read(abData, 0, abData.length);
                if (nBytesRead >= 0) {
                    auline.write(abData, 0, nBytesRead);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        } finally {
            auline.drain();
            auline.close();
        }
    }
    // </editor-fold>
}
